# -*- coding: utf-8 -*-
"""
Created on Wed Sep 25 22:22:00 2019

@author: swls_vanlance
"""

import json
import shutil
import os
import sys
import requests
import base64
# import cv2
from tqdm import tqdm
import numpy as np
from collections import defaultdict

# root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(root_dir)
# from os_tool.os_tool import get_all_filepath

def rename(data_dir, dest_dir):
    for p in os.listdir(data_dir):
        new_path = dest_dir+ os.sep + p.replace("0_polygon", "data")
        shutil.copy(data_dir +os.sep +  p, new_path)

def mean_distuibute_image(path_dir, tag):
    all_paths = get_all_img(path_dir, tag)

    count = 0
    every_image_num_in_dir= 500
    for idx, f in tqdm(enumerate(all_paths)):
        sub_dir = path_dir + os.sep + str(int(idx / every_image_num_in_dir))
        if not os.path.exists(sub_dir):
            os.makedirs(sub_dir)
        
        shutil.move(f, sub_dir + os.sep + os.path.basename(f))

# def filter_yellow_image(path_dir, dest_dir, tag):
#     all_paths = get_all_filepath(path_dir, tag)

#     count = 0
#     for f in tqdm(all_paths):
#         image = cv2.imread(f)
#         if 130 < np.mean(image) < 160:
#             count += 1
#             shutil.move(f, dest_dir + os.sep + os.path.basename(f))

def cat_all(data_dir):
    # price_level = 0.02
    price_level = [0.01, 0.03, 0.06 , 0.08 , 0.10 , 0.12 , 0.14 , 0.16 , 0.18 , 0.20 , 0.22 , 0.24, 0.26,0.28,0.30,0.32,0.34,0.36]
    price_list = [0.01, 0.03, 0.06 + 0.005, 0.08 + 0.010, 0.10 + 0.015, 0.12 + 0.020, 0.14 + 0.025, 0.16 + 0.030, 
                    0.18 +0.035, 0.20 + 0.040, 0.22 + 0.045, 0.24 + 0.050, 0.26 + 0.055,0.28 + 0.060,0.30 + 0.065,
                    0.32 + 0.070,0.34 + 0.075,0.36 + 0.080]
    char_step = 5

    # all_price = 0
    all_price_new = 0
    all_text_line = 0
    all_char = 0
    all_black_image = 0
    all_image_num = 0
    default_d = defaultdict(int)

    for p in os.listdir(data_dir):
        all_image_num += 1
        black_image_flag = True
        with open(data_dir + os.sep + p, "r") as rf:
            one_file = json.loads(rf.read())
        all_text_data = one_file["text_polygon"]
        if type(all_text_data) == list:
            black_image_flag = False
            for i in all_text_data:
                text = i["text"]
                print(text)
                
                length = len(i["text"])
                default_d[str(length)] += 1
                all_char += length
                all_text_line += 1

                # all_price += (int(length / char_step) + 1) * (price_level)
                idx = int(length / char_step)
                all_price_new += price_list[idx] + ((price_level[idx+1] - price_level[idx]) * ((length % char_step) / char_step))


        all_watermark_data = one_file.get("watermark_polygon", None)
        if type(all_watermark_data) == list:
            black_image_flag = False
            for i in all_watermark_data:
                text = i["text"]
                print(text)

                length = len(i["text"])
                default_d[str(length)] += 1
                all_char += length
                all_text_line += 1

                # all_price += (int(length / char_step) + 1) * (price_level)
                idx = int(length / char_step)
                all_price_new += price_list[idx] + ((price_level[idx+1] - price_level[idx]) * (length % char_step))

        if black_image_flag:
            all_black_image += 1
        print("\n\n")
    # print("all_text_line: ", all_text_line)
    # print("all_black_image: ", all_black_image)

    # 计价方式2：{} x 0.4 + {} x 0.1 = {}
    print("修改后文本行{}， 文字图片数量{}，空白图片数量{} 。计价方式1：{} x 0.05 + {} x 0.1 = {}。  ".format(
        str(all_text_line),
        str(all_image_num - all_black_image),
        str(all_black_image),
        str(all_text_line),
        str(all_black_image),
        str(all_text_line * 0.05 + all_black_image * 0.1),
        # str(all_image_num - all_black_image),
        # str(all_black_image),
        # str((all_image_num - all_black_image) * 0.4 + all_black_image * 0.1)
    ))

    distribute_info = [(int(k), v) for k,v in default_d.items()]
    distribute_info = sorted(distribute_info, key=lambda x: x[0])
    idx = ''.join(["{:>4}".format(s[0]) for s in distribute_info])
    value = ''.join(["{:>4}".format(s[1]) for s in distribute_info])
    print("分布: ")
    print(idx ,"\n", value)
    print("所有字符数: ", all_char)
    # print("all_price: ", all_price)
    print("采用新计算方式后价格: ", all_price_new)


def move_file_to_new(src_image_dir, src_json_dir, dest_dir):
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)
    all_name = [p.split(".")[0].split("_")[0] for p in os.listdir(src_json_dir)]
    for p in os.listdir(src_image_dir):
        if p.split(".")[0] in all_name:
            new_path = dest_dir + os.sep + p
            shutil.copy(src_image_dir + os.sep + p, new_path)

def recog(file_path):
    with open(file_path,'rb') as f:
        str_ = base64.b64encode(f.read())
    data = {'upload_file':str_,'file_type':'jpg'}
    url = 'http://122.112.143.200:80'

    header = {
            'Connection':'close'
        }
    r = requests.post(url=url, data=data,headers=header)
    text_info = json.loads(r.text)["text_info"]
    print(text_info[0]["text_data"])



def check_file_is_exists(src_image_dir, src_json_dir):
    # if not os.path.exists(dest_dir):
    #     os.mkdir(dest_dir)
    all_name = [p.split(".")[0].split("_")[0] for p in os.listdir(src_json_dir)]
    for p in os.listdir(src_image_dir):
        if not p.split(".")[0] in all_name:
            print(p)
            # new_path = dest_dir + os.sep + p
            # shutil.copy(src_image_dir + os.sep + p, new_path)

# 根据json文件删除多余的图片
def remove_other_image(img_dir, json_dir):
    all_imag_name = [p.split(".")[0] for p in os.listdir(img_dir)]

    for p in os.listdir(json_dir):
        json_img_name = p.split(".")[0].split("_")[0]
        for i,name in enumerate(all_imag_name):
            if name == json_img_name:
                del all_imag_name[i]
                break

    print(all_imag_name)

if __name__ == "__main__":

    # dest = sys.argv[2]
    # rename(path, dest) 


    path = sys.argv[1]                      # 传入参数：存放json的文件目录
    cat_all(path)                           # 查看所有json文件

    # img_dir = sys.argv[1]
    # json_dir = sys.argv[2]
    # remove_other_image(img_dir, json_dir)

    # name_list = ["张东洋", "房浩然", "赵维义", "孙艺洁 " ,"岑曾迪", "杜宇航", "张婷怡", "贾宇豪", "宋小雨", "刘颖"  ]
    # path = "C:\\Users\\swls\\Desktop\\bj\\bj\\00\\{}_check"
    # for idx,name in enumerate(name_list):
    #     new_path = path.format(idx)
    #     if not os.path.exists(new_path):
    #         continue
    #     print(name + "  " + str(idx))
    #     cat_all(new_path)


    # src_image_dir = 'C:\\Users\\swls\\Desktop\\bj\\bj\\00\\9'
    # src_json_dir = "C:\\Users\\swls\\Desktop\\bj\\bj\\00\\9_9"
    # dest_dir  = "C:\\Users\\swls\\Desktop\\bj\\bj\\00\\9_check"
    # move_file_to_new(src_image_dir, src_json_dir, dest_dir)

    # path = sys.argv[1]
    # recog(path)


    # path_dir = r"F:\sunjie\images\34_tar\0"
    # dest_dir = r"F:\sunjie\images\34_tar\yellow_all"
    # tag = ["jpg", "jpeg", "png", "bmp"]
    # mean_distuibute_image(path_dir, tag)


    # path_dir = r"F:\sunjie\images\34_tar\0"
    # dest_dir = r"F:\sunjie\images\34_tar\yellow_all"
    # tag = ["jpg", "jpeg", "png", "bmp"]
    # filter_yellow_image(path_dir, dest_dir, tag)


    # src_image_dir = 'C:\\Users\\swls\\Desktop\\bj\\bj\\00\\6'
    # src_json_dir = "C:\\Users\\swls\\Desktop\\bj\\bj\\00\\6_check"
    # check_file_is_exists(src_image_dir, src_json_dir)


